#import "AnalogClock.h"
#import <QuartzCore/QuartzCore.h>

@implementation AnalogClock

inline double rad(double deg)
{
	return deg / 180.0 * M_PI;
}

- (void) drawLineForContext:(const CGContextRef&)context Width:(float)_width angle:(double)_angle length:(double)radius
{
	CGPoint c = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0);
	
	CGContextSetLineWidth(context, _width);
	CGContextMoveToPoint(context, self.center.x, self.center.y);
	CGPoint addLines[] =
	{
        //		CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0),
		CGPointMake(0.1*(-radius*cos(_angle)) +c.x, 0.1*(-radius*sin(_angle)) +c.y),
		CGPointMake(radius*cos(_angle) +c.x, radius*sin(_angle) +c.y),
	};
	
	CGContextAddLines(context, addLines, sizeof(addLines)/sizeof(addLines[0]));
	CGContextStrokePath(context);
}

- (void)drawRect:(CGRect)rect 
{
	NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDate* now = [NSDate date];	
	int h = [[cal components:NSHourCalendarUnit fromDate:now] hour];
	int m = [[cal components:NSMinuteCalendarUnit fromDate:now] minute];
	int s = [[cal components:NSSecondCalendarUnit fromDate:now] second];
	[cal release];
	
	BOOL isAM = h<12;
	double hAlpha = rad((isAM?h:h-12)*30 +(30*m/60) -90);
	double mAlpha = rad(m*6 -90);
	double sAlpha = rad(s*6 -90);

	CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);	
	[self drawLineForContext:context Width:5.0 angle:hAlpha length:self.frame.size.width/2.0 - 18];
	[self drawLineForContext:context Width:5.0 angle:mAlpha length:self.frame.size.width/2.0 - 12];
	CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
	[self drawLineForContext:context Width:2.0 angle:sAlpha length:self.frame.size.width/2.0 - 10];
    
    // Draw a circle (filled)
    CGContextSetRGBFillColor(context, 1.0, 0, 0, 1);    
    CGContextFillEllipseInRect(context, CGRectMake(155, 225, 10, 10));
}

-(void)update
{
	[self setNeedsDisplay];
}

-(void)startClockUpdates
{
	[self update];
	timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
}
-(void)stopClockUpdates
{
	[timer invalidate], timer = nil;
}

-(void)dealloc
{
	[self stopClockUpdates];
    [super dealloc];
}

@end